#include "qmyartiklilista.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>

#include <QDesktopWidget>
#include "chelperclass.h"
#include <QMessageBox>





QMyArtikliLista::QMyArtikliLista(QWidget *parent)
	: QMyBaseFormWidget(parent)
	,m_selectedText("")
	,m_selectedTextName("")
	, m_row(0)
	,m_offset(0)
	
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
 	ui.tabWidget->setFixedWidth(deskRect.width() - 300);
	ui.tabWidget->setFixedHeight(deskRect.height()-200);

	lista("%%%");
	ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
    connect(ui.checkBox, SIGNAL(clicked()), this, SLOT(checkBox_clicked()));
    connect(ui.pushButton_4, SIGNAL(clicked()), this, SLOT(pushButton4_clicked()));
	connect(ui.prevButton, SIGNAL(clicked()), this, SLOT(prevButtonPressed()));
	connect(ui.nextButton, SIGNAL(clicked()), this, SLOT(nextButtonPressed()));


    ui.lineEdit->setFocus();

}

QMyArtikliLista::~QMyArtikliLista()
{

}

void QMyArtikliLista::setRow(int mrow)
{
	ui.tableView->selectRow(mrow);
	ui.tableView->setFocus();
}

void QMyArtikliLista::prevButtonPressed()
{
	m_offset = m_offset <= 50 ? 0 : m_offset - 50;
	lista(ui.lineEdit->text());
}


void QMyArtikliLista::nextButtonPressed()
{
	m_offset += 50;
	lista(ui.lineEdit->text());
}

int QMyArtikliLista::getRow()
{
	int m_row = -1;
	QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
	if (indexes.count())
	{
		m_row = indexes.at(0).row();
	}
	return m_row;
}

QString QMyArtikliLista::getSearchStr()
{
	return ui.lineEdit->text();
}


void QMyArtikliLista::setSearchStr(QString mSearchStr)
{
	ui.lineEdit->setText(mSearchStr);
}

void QMyArtikliLista::checkBox_clicked()
{
	lista(ui.lineEdit->text());
}

QString QMyArtikliLista::getLine()
{
    return ui.lineEdit->text();
}



void QMyArtikliLista::lista(const QString& nameSearch)
{
    bool isNumeric = false;
    nameSearch.toInt(&isNumeric); 

    int r = 0;
    int c = 13;
    int fieldNo[13];
    QString country[13];
    int colWidth[] = {70, 50, 250, 60, 60, 100 , 100 , 100 , 100 , 100, 50, 250, 0};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ref", "kataloski_broj", "art_nabavna_cena", "art_nabavna_cena_valuta",
        "art_prodazna_cena", "art_prodazna_cena_valuta" ,"ddv", "proizvoditel", "kategorija"};
    QString temp = "";
    if ( isNumeric )
    {
        temp = "select id, sifra, artikal, edm, ref, kataloski_broj, "
            "art_nabavna_cena, art_nabavna_cena_valuta,  "
            "art_prodazna_cena, art_prodazna_cena_valuta, ddv, proizvoditel, kategorija "
            " from artikli where sifra = '";
        temp += nameSearch;
        temp += "%' limit 50 OFFSET "+ QString::number(m_offset, 10);
    }
    else
    {
        temp = "select id, sifra, artikal, edm, ref, kataloski_broj, "
            "art_nabavna_cena, art_nabavna_cena_valuta,  "
            "art_prodazna_cena, art_prodazna_cena_valuta, ddv, proizvoditel, kategorija "
            " from artikli where artikal like '";
        temp += nameSearch;
		temp += "%' limit 50 OFFSET "+ QString::number(m_offset, 10);

    }	
    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Id."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм"));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("Реф"));
    model->setHeaderData( 5, Qt::Horizontal, trUtf8("Каталошки број"));
    model->setHeaderData( 6, Qt::Horizontal, trUtf8("Набавна цена"));
    model->setHeaderData( 7, Qt::Horizontal, trUtf8("Набавна цена со ДДВ"));
    model->setHeaderData( 8, Qt::Horizontal, trUtf8("Продажна цена"));
    model->setHeaderData( 9, Qt::Horizontal, trUtf8("Продажна цена со ДДВ"));
    model->setHeaderData( 10, Qt::Horizontal, trUtf8("ДДВ"));
	model->setHeaderData( 11, Qt::Horizontal, trUtf8("Производител"));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
    QLocale loc;
    QString temp1 = "";
    CHelperClass chc(this);
    chc.createArtikliSoNormativMap();
	setUpdatesEnabled(false);
	while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QStandardItem *item = new QStandardItem("");
            fieldNo[i] = query.record().indexOf(colName[i]);

            if (i > 5 && i < 11) 
            {
                temp1 = loc.toString(query.value(fieldNo[i]).toFloat(), 'f', 2);
            }
            else
            {
                temp1 = query.value(fieldNo[i]).toString();
            }

            if (i == 0)
            {
                temp1 = query.value(fieldNo[0]).toString();
                item->setText(temp1);
                chc.getArtikalStatus(item);
            }
            item->setText(temp1);
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
        row++;
    } 
	setUpdatesEnabled(true);

	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
}

void QMyArtikliLista::on_lineEdit_textChanged(const QString &)
{
	m_offset = 0;
	lista(ui.lineEdit->text());
}



void QMyArtikliLista::on_tableView_clicked(const QModelIndex &modelX)
{
	int i = modelX.row();
	m_row = modelX.row();
	m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
}


void QMyArtikliLista::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
    m_selectedTextName = model->item(i, 2) ? model->item(i, 2)->text():"";

    ui.lineEdit_2->setText(model->item(i, 0)->text());
    ui.lineEdit_3->setText(model->item(i, 1)->text());
    ui.lineEdit_4->setText(model->item(i, 2)->text());
    ui.lineEdit_5->setText(model->item(i, 3)->text());
    ui.lineEdit_6->setText(model->item(i, 4)->text());
    ui.lineEdit_7->setText(model->item(i, 5)->text());
    ui.lineEdit_8->setText(model->item(i, 6)->text());
    ui.lineEdit_9->setText(model->item(i, 7)->text());
    ui.lineEdit_10->setText(model->item(i, 8)->text());
    ui.lineEdit_11->setText(model->item(i, 9)->text());
    ui.lineEdit_12->setText(model->item(i, 10)->text());
	ui.lineEdit_13->setText(model->item(i, 11)->text());
    QString textTemp = model->item(i, 12)->text();
    if (textTemp.contains("1"))
    {
        ui.checkBox_2->setDisabled(true);
        ui.checkBox_2->setChecked(true);
    }
    else
    {
        ui.checkBox_2->setDisabled(true);
        ui.checkBox_2->setChecked(false);
    }
}


void QMyArtikliLista::setFocusSearchField()
{
	ui.lineEdit->setFocus();
}

void QMyArtikliLista::pressEscape()
{
	emit closeW();
}

void QMyArtikliLista::pressReturn()
{
    if (ui.lineEdit->hasFocus())
    {
        ui.tableView->setFocus();
    }
    else if (ui.tableView->hasFocus())
	{
		emit sArtikalToPriemnica(m_selectedText, m_selectedTextName);	
	}

}

void QMyArtikliLista::setInitText(QString text)
{
	ui.lineEdit->setText(text);
	ui.lineEdit->selectAll();
	ui.lineEdit->setFocus();
}

void QMyArtikliLista::on_pushButton_clicked()
{
    emit procF2();
}
void QMyArtikliLista::on_pushButton_2_clicked()
{
    emit procF3();
}

void QMyArtikliLista::on_lineEdit_15_textChanged(const QString &)
{
    listaA(ui.lineEdit_15->text());
}

void QMyArtikliLista::listaA(const QString& nameSearch)
{
    if (nameSearch.length() < 0)
    {
        ui.tableView_2->hide();
        return;
    }
    if (nameSearch.length() < 2)
    {
        return;
    }
    bool isNumeric = false;
    nameSearch.toInt(&isNumeric); 

    int r = 0;
    int c = 13;
    int fieldNo[13];
    QString country[13];
    int colWidth[] = {70, 50, 250, 60, 60, 100 , 100 , 100 , 100 , 100, 50, 250, 0};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ref", "kataloski_broj", "art_nabavna_cena", "art_nabavna_cena_valuta",
        "art_prodazna_cena", "art_prodazna_cena_valuta" ,"ddv", "proizvoditel", "kategorija"};
    QString temp = "";
    if ( isNumeric )
    {
        temp = "select id, sifra, artikal, edm, ref, kataloski_broj, "
            "art_nabavna_cena, art_nabavna_cena_valuta,  "
            "art_prodazna_cena, art_prodazna_cena_valuta, ddv, proizvoditel, kategorija "
            " from artikli where sifra = '";
        temp += nameSearch;
        if (ui.checkBox->isChecked())
        {
            temp += "%' limit 100000";
        }
        else
        {
            temp += "%' limit 20";
        }
    }
    else
    {
        temp = "select id, sifra, artikal, edm, ref, kataloski_broj, "
            "art_nabavna_cena, art_nabavna_cena_valuta,  "
            "art_prodazna_cena, art_prodazna_cena_valuta, ddv, proizvoditel, kategorija "
            " from artikli where artikal like '";
        temp += nameSearch;
        if (ui.checkBox->isChecked())
        {
            temp += "%' limit 100000";
        }
        else
        {
            temp += "%' limit 200";
        }
    }	
    QSqlQuery query(temp);
    model2 = new QStandardItemModel(r,c);
    model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Id."));
    model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм"));
    model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Реф"));
    model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Каталошки број"));
    model2->setHeaderData( 6, Qt::Horizontal, trUtf8("Набавна цена"));
    model2->setHeaderData( 7, Qt::Horizontal, trUtf8("Набавна цена со ДДВ"));
    model2->setHeaderData( 8, Qt::Horizontal, trUtf8("Продажна цена"));
    model2->setHeaderData( 9, Qt::Horizontal, trUtf8("Продажна цена со ДДВ"));
    model2->setHeaderData( 10, Qt::Horizontal, trUtf8("ДДВ"));
    model2->setHeaderData( 11, Qt::Horizontal, trUtf8("Производител"));

    ui.tableView_2->setModel(model2);
    header = new QHeaderView(Qt::Horizontal, this);
    header->setClickable(true);
    ui.tableView_2->setHorizontalHeader(header);
    header->show();
    int row = 0;
    QLocale loc;
    QString temp1 = "";
    CHelperClass chc(this);
    chc.createArtikliSoNormativMap();
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QStandardItem *item = new QStandardItem("");
            fieldNo[i] = query.record().indexOf(colName[i]);

            if (i > 5 && i < 11) 
            {
                temp1 = loc.toString(query.value(fieldNo[i]).toFloat(), 'f', 2);
            }
            else
            {
                temp1 = query.value(fieldNo[i]).toString();
            }

            if (i == 0)
            {
                temp1 = query.value(fieldNo[0]).toString();
                item->setText(temp1);
                chc.getArtikalStatus(item);
            }
            item->setText(temp1);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(row, 18);
            ui.tableView_2->setColumnWidth(i, colWidth[i]);
            model2->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView_2->selectionModel();
     connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
         this, SLOT(selectionChangedA(QModelIndex,QModelIndex)));
    ui.tableView_2->show();
}

void QMyArtikliLista::on_lineEdit_16_textChanged(const QString &)
{
    listaB(ui.lineEdit_16->text());
}

void QMyArtikliLista::listaB(const QString& nameSearch)
{
    if (nameSearch.length() < 0)
    {
        ui.tableView_3->hide();
        return;
    }
    if (nameSearch.length() < 2)
    {
        return;
    }
    bool isNumeric = false;
    nameSearch.toInt(&isNumeric); 

    int r = 0;
    int c = 13;
    int fieldNo[13];
    QString country[13];
    int colWidth[] = {70, 50, 250, 60, 60, 100 , 100 , 100 , 100 , 100, 50, 250, 0};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ref", "kataloski_broj", "art_nabavna_cena", "art_nabavna_cena_valuta",
        "art_prodazna_cena", "art_prodazna_cena_valuta" ,"ddv", "proizvoditel", "kategorija"};
    QString temp = "";
    if ( isNumeric )
    {
        temp = "select id, sifra, artikal, edm, ref, kataloski_broj, "
            "art_nabavna_cena, art_nabavna_cena_valuta,  "
            "art_prodazna_cena, art_prodazna_cena_valuta, ddv, proizvoditel, kategorija "
            " from artikli where sifra = '";
        temp += nameSearch;
        if (ui.checkBox->isChecked())
        {
            temp += "%' limit 100000";
        }
        else
        {
            temp += "%' limit 200";
        }
    }
    else
    {
        temp = "select id, sifra, artikal, edm, ref, kataloski_broj, "
            "art_nabavna_cena, art_nabavna_cena_valuta,  "
            "art_prodazna_cena, art_prodazna_cena_valuta, ddv, proizvoditel, kategorija "
            " from artikli where artikal like '";
        temp += nameSearch;
        if (ui.checkBox->isChecked())
        {
            temp += "%' limit 100000";
        }
        else
        {
            temp += "%' limit 20";
        }
    }	
    QSqlQuery query(temp);
    model3 = new QStandardItemModel(r,c);
    model3->setHeaderData( 0, Qt::Horizontal, trUtf8("Id."));
    model3->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model3->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model3->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм"));
    model3->setHeaderData( 4, Qt::Horizontal, trUtf8("Реф"));
    model3->setHeaderData( 5, Qt::Horizontal, trUtf8("Каталошки број"));
    model3->setHeaderData( 6, Qt::Horizontal, trUtf8("Набавна цена"));
    model3->setHeaderData( 7, Qt::Horizontal, trUtf8("Набавна цена со ДДВ"));
    model3->setHeaderData( 8, Qt::Horizontal, trUtf8("Продажна цена"));
    model3->setHeaderData( 9, Qt::Horizontal, trUtf8("Продажна цена со ДДВ"));
    model3->setHeaderData( 10, Qt::Horizontal, trUtf8("ДДВ"));
    model3->setHeaderData( 11, Qt::Horizontal, trUtf8("Производител"));

    ui.tableView_3->setModel(model3);
    header = new QHeaderView(Qt::Horizontal, this);
    header->setClickable(true);
    ui.tableView_3->setHorizontalHeader(header);
    header->show();
    int row = 0;
    QLocale loc;
    QString temp1 = "";
    CHelperClass chc(this);
    chc.createArtikliSoNormativMap();
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QStandardItem *item = new QStandardItem("");
            fieldNo[i] = query.record().indexOf(colName[i]);

            if (i > 5 && i < 11) 
            {
                temp1 = loc.toString(query.value(fieldNo[i]).toFloat(), 'f', 2);
            }
            else
            {
                temp1 = query.value(fieldNo[i]).toString();
            }

            if (i == 0)
            {
                temp1 = query.value(fieldNo[0]).toString();
                item->setText(temp1);
                chc.getArtikalStatus(item);
            }
            item->setText(temp1);
            item->setEditable(false);
            ui.tableView_3->setRowHeight(row, 18);
            ui.tableView_3->setColumnWidth(i, colWidth[i]);
            model3->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView_3->selectionModel();
         connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
             this, SLOT(selectionChangedB(QModelIndex,QModelIndex)));
    ui.tableView_3->show();
}


void QMyArtikliLista::selectionChangedA(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    ui.lineEdit_17->setText(model2->item(i, 0)->text());
    ui.lineEdit_18->setText(model2->item(i, 1)->text());
    ui.lineEdit_19->setText(model2->item(i, 2)->text());
    ui.lineEdit_20->setText(model2->item(i, 3)->text());
}

void QMyArtikliLista::selectionChangedB(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    ui.lineEdit_23->setText(model3->item(i, 0)->text());
    ui.lineEdit_24->setText(model3->item(i, 1)->text());
    ui.lineEdit_25->setText(model3->item(i, 2)->text());
    ui.lineEdit_26->setText(model3->item(i, 3)->text());
}

void QMyArtikliLista::pushButton4_clicked()
{
    if((!ui.lineEdit_17->text().isEmpty())&&(!ui.lineEdit_23->text().isEmpty()&&(ui.lineEdit_17->text() != ui.lineEdit_23->text())))
    {
        
        QMessageBox msgBox;
        msgBox.setText(trUtf8("Артиклите ке бидат споени. \nЗалихите од левиот артикал ке бидат \nпренесени кај десниот артикал \nи левиот артикал ке биде \nцелосно избришан! "));
        msgBox.setInformativeText(trUtf8("Дали сакате да ги направите овие промените?"));
        msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Ok);	int ret = msgBox.exec();
        if (ret == QMessageBox::Ok )
        {

            QLocale loc;
            int mid=0;

            QSqlDatabase db = QSqlDatabase::database();
            db.transaction();	
            bool sqlStat = true;
            QSqlQuery query1;
            query1.clear();
            query1.prepare("update magacin set artikal_id = :a1 where artikal_id = :a0");
            query1.bindValue(":a0", ui.lineEdit_17->text());	
            query1.bindValue(":a1", ui.lineEdit_23->text());	
            sqlStat = sqlStat && query1.exec();

            query1.clear();
            query1.prepare("update finansovi_stavki set artikal_id = :a1 where artikal_id = :a0");
            query1.bindValue(":a0", ui.lineEdit_17->text());	
            query1.bindValue(":a1", ui.lineEdit_23->text());	
            sqlStat = sqlStat && query1.exec();


            query1.clear();
            query1.prepare("update proizvodi_sostav set id_artikal = :a1 where id_artikal = :a0");
            query1.bindValue(":a0", ui.lineEdit_17->text());	
            query1.bindValue(":a1", ui.lineEdit_23->text());	
            sqlStat = sqlStat && query1.exec();

            query1.clear();
            query1.prepare("update proizvodi_sostav set id_proizvod = :a1 where id_proizvod = :a0");
            query1.bindValue(":a0", ui.lineEdit_17->text());	
            query1.bindValue(":a1", ui.lineEdit_23->text());	
            sqlStat = sqlStat && query1.exec();

            query1.clear();
            query1.prepare("delete from artikli where id = :a0");
            query1.bindValue(":a0", ui.lineEdit_17->text());	
            sqlStat = sqlStat && query1.exec();

			query1.clear();
			query1.prepare("delete from proizvodi_sostav where id_proizvod = id_artikal");
			sqlStat = sqlStat && query1.exec();

            if (sqlStat)
            {
                db.commit();
                QMessageBox msgBox;
                msgBox.setText(trUtf8("Артиклите се успешно споени"));
                msgBox.setStandardButtons(QMessageBox::Ok);
                msgBox.setDefaultButton(QMessageBox::Ok);
                listaA("0000");
                listaB("0000");
                ui.lineEdit_17->setText("");
                ui.lineEdit_18->setText("");
                ui.lineEdit_19->setText("");
                ui.lineEdit_20->setText("");
                msgBox.exec();
            } 
            else
            {
                db.rollback();
                QMessageBox msgBox;
                msgBox.setText(trUtf8("Артиклите НЕ се успешно споени!!!."));
                msgBox.setStandardButtons(QMessageBox::Ok);
                msgBox.setDefaultButton(QMessageBox::Ok);
                msgBox.exec();
            }
        }
    }
}

